<template>
  <el-input v-model="inputValue" size="large" class="phone-var-code" placeholder="请输入验证码" @blur="updateValue">
    <template #append>
      <div :class="{ 'var-code-btn': true, 'btn-disabled': !canGetVarCode }" @click="beforeGetVarCode">
        {{ varCodeTips }}
      </div>
      <SlideVerify @onSuccess="getVarCode" v-model:show="verifyShow" />
    </template>
  </el-input>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch, onBeforeUnmount } from 'vue'
import { getPhoneVarCode } from '@/api/user'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  phone: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    default: ''
  },
  countdown: {
    type: Number,
    default: 60
  }
})

// 定义emit
const emit = defineEmits(['update:modelValue'])

const inputValue = ref(props.modelValue)
const canGetVarCode = ref(true)
const varCodeTips = ref('获取验证码')
let timer = null
let remainingTime = ref(props.countdown)

// 监听value变化
watch(
  () => props.modelValue,
  newVal => {
    inputValue.value = newVal
  }
)

// 倒计时函数
const startCountdown = () => {
  varCodeTips.value = `重新发送(${remainingTime.value}秒)`
  canGetVarCode.value = false

  timer = setInterval(() => {
    remainingTime.value--
    varCodeTips.value = `重新发送(${remainingTime.value}秒)`

    if (remainingTime.value <= 0) {
      clearInterval(timer)
      varCodeTips.value = '获取验证码'
      canGetVarCode.value = true
      remainingTime.value = props.countdown
    }
  }, 1000)
}

// 获取验证码前置校验
const verifyShow = ref(false)
const beforeGetVarCode = () => {
  if (!props.phone) {
    ElMessage.error('手机号不能为空')
    return
  }
  verifyShow.value = true
}

// 获取验证码
const getVarCode = async () => {
  if (!canGetVarCode.value) return

  try {
    const terminal = navigator.userAgent.match(/AppleWebKit.*Mobile.*/) ? '2' : '1'
    const res = await getPhoneVarCode({
      account: props.phone,
      terminal
    })
    if (res.code === 20000) {
      startCountdown()
      ElMessage.success('验证码已发送')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 更新值
const updateValue = () => {
  emit('update:modelValue', inputValue.value)
}

// 组件销毁时清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped lang="scss">
p.login-label {
  font-size: 14px;
  margin-bottom: 10px;
  line-height: 16px;
}
.phone-var-code {
  ::v-deep .el-input-group__append {
    background-color: #fff;
    padding: 0;
  }
  .var-code-btn {
    min-width: 130px;
    height: 20px;
    line-height: 20px;
    padding: 0 15px;
    cursor: pointer;
    color: $mainColor;
    box-sizing: border-box;
    text-align: center;
  }
  .var-code-btn.btn-disabled {
    color: $black_tips;
    cursor: default;
  }
}
</style>
